// 游戏引擎核心类
class GameEngine {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.gameState = 'menu'; // 'menu', 'playing', 'paused', 'gameOver', 'levelComplete', 'levelIntro'
        this.lastTime = 0;
        this.fps = 60;
        this.frameInterval = 1000 / this.fps;
        
        // 游戏对象数组
        this.entities = [];
        this.bullets = [];
        this.zombies = [];
        this.weapons = [];
        this.meleeWeapons = []; // 近战武器数组
        this.particles = [];
        this.powerUps = [];
        this.floatingTexts = [];
        this.bossProjectiles = [];
        this.zombieProjectiles = []; // 僵尸投射物数组 - 安全初始化
        this.boss = null;
        
        // 确保投射物数组始终可用
        this.ensureProjectileArrays();
        
        // 输入处理
        this.keys = {};
        this.mouse = { x: 0, y: 0, down: false };
        
        // 摄像机系统
        this.camera = { x: 0, y: 0 };
        
        this.setupEventListeners();
        this.setupPixelArt();
    }
    
    // 确保投射物数组始终存在且有效
    ensureProjectileArrays() {
        if (!Array.isArray(this.zombieProjectiles)) {
            this.zombieProjectiles = [];
            console.log('重置僵尸投射物数组');
        }
        if (!Array.isArray(this.bossProjectiles)) {
            this.bossProjectiles = [];
            console.log('重置Boss投射物数组');
        }
        if (!Array.isArray(this.bullets)) {
            this.bullets = [];
            console.log('重置子弹数组');
        }
        if (!Array.isArray(this.particles)) {
            this.particles = [];
            console.log('重置粒子数组');
        }
    }
    
    // 安全添加僵尸投射物
    addZombieProjectile(projectile) {
        try {
            // 确保数组存在
            this.ensureProjectileArrays();
            
            // 验证投射物数据
            if (!projectile || typeof projectile !== 'object') {
                console.warn('无效的投射物数据:', projectile);
                return false;
            }
            
            // 设置默认值
            const safeProjectile = {
                x: Number(projectile.x) || 0,
                y: Number(projectile.y) || 0,
                vx: Number(projectile.vx) || 0,
                vy: Number(projectile.vy) || 0,
                damage: Number(projectile.damage) || 10,
                radius: Number(projectile.radius) || 5,
                life: Number(projectile.life) || 2000,
                maxLife: Number(projectile.life) || 2000,
                type: String(projectile.type) || 'spit',
                color: String(projectile.color) || '#90EE90'
            };
            
            // 检查投射物数量限制 - 优先保护BOSS投射物
            if (this.zombieProjectiles.length >= 30) {
                console.warn('投射物数量已达上限，智能清理投射物');
                this.smartCleanProjectiles();
            }
            
            // 添加到数组
            this.zombieProjectiles.push(safeProjectile);
            console.log('成功添加僵尸投射物:', safeProjectile.type);
            return true;
            
        } catch (error) {
            console.error('添加僵尸投射物失败:', error);
            return false;
        }
    }
    
    // 智能投射物清理 - 优先保护BOSS投射物
    smartCleanProjectiles() {
        try {
            if (!this.zombieProjectiles || this.zombieProjectiles.length === 0) return;
            
            // 分类投射物：BOSS投射物 vs 普通投射物
            const bossProjectiles = [];
            const normalProjectiles = [];
            
            this.zombieProjectiles.forEach(projectile => {
                if (projectile.isBossProjectile || projectile.priority === 'high') {
                    bossProjectiles.push(projectile);
                } else {
                    normalProjectiles.push(projectile);
                }
            });
            
            // 优先清理普通投射物
            if (normalProjectiles.length > 0) {
                // 移除一半的普通投射物
                const toRemove = Math.ceil(normalProjectiles.length / 2);
                normalProjectiles.splice(0, toRemove);
                console.log(`智能清理：移除了 ${toRemove} 个普通投射物`);
            }
            
            // 如果还是太多，才清理一些老的BOSS投射物
            const totalAfterClean = bossProjectiles.length + normalProjectiles.length;
            if (totalAfterClean > 25) {
                const excessBoss = totalAfterClean - 25;
                bossProjectiles.splice(0, excessBoss);
                console.log(`智能清理：移除了 ${excessBoss} 个BOSS投射物`);
            }
            
            // 重新组合数组，BOSS投射物放在前面（优先渲染）
            this.zombieProjectiles = [...bossProjectiles, ...normalProjectiles];
            
        } catch (cleanError) {
            console.error('智能清理投射物失败:', cleanError);
            // 失败时执行简单清理
            if (this.zombieProjectiles.length > 20) {
                this.zombieProjectiles = this.zombieProjectiles.slice(-20);
            }
        }
    }
    
    setupPixelArt() {
        // 确保像素艺术风格
        this.ctx.imageSmoothingEnabled = false;
        this.ctx.webkitImageSmoothingEnabled = false;
        this.ctx.mozImageSmoothingEnabled = false;
        this.ctx.msImageSmoothingEnabled = false;
    }
    
    setupEventListeners() {
        // 键盘事件
        document.addEventListener('keydown', (e) => {
            this.keys[e.code] = true;
            
            // 特殊按键处理
            if (e.code === 'Space') {
                e.preventDefault();
                if (this.gameState === 'playing' && window.player && window.player.combatMode === 'ranged') {
                    // 只有在远程模式下才能换弹
                    window.player.quickReload();
                }
            }
            
            if (e.code === 'KeyE') {
                if (this.gameState === 'playing' && window.player) {
                    // 传递远程武器数组，近战武器在pickupNearestWeapon方法内部处理
                    window.player.pickupNearestWeapon(this.weapons);
                }
            }
        });
        
        document.addEventListener('keyup', (e) => {
            this.keys[e.code] = false;
        });
        
        // 鼠标事件
        this.canvas.addEventListener('mousemove', (e) => {
            const rect = this.canvas.getBoundingClientRect();
            this.mouse.x = e.clientX - rect.left;
            this.mouse.y = e.clientY - rect.top;
        });
        
        this.canvas.addEventListener('mousedown', (e) => {
            this.mouse.down = true;
            if (this.gameState === 'playing' && window.player) {
                // 根据战斗模式选择攻击方式
                if (window.player.combatMode === 'ranged') {
                    window.player.shoot(this.mouse.x, this.mouse.y);
                } else if (window.player.combatMode === 'melee') {
                    window.player.performMeleeAttack(this.mouse.x, this.mouse.y);
                }
            }
        });
        
        this.canvas.addEventListener('mouseup', () => {
            this.mouse.down = false;
        });
        
        // 防止右键菜单
        this.canvas.addEventListener('contextmenu', (e) => {
            e.preventDefault();
        });
    }
    
    start() {
        this.gameLoop();
    }
    
    gameLoop(currentTime = 0) {
        const deltaTime = currentTime - this.lastTime;
        
        if (deltaTime >= this.frameInterval) {
            this.update(deltaTime);
            this.render();
            this.lastTime = currentTime;
        }
        
        requestAnimationFrame((time) => this.gameLoop(time));
    }
    
    update(deltaTime) {
        if (this.gameState !== 'playing') {
            // 在非playing状态下，只更新安全的UI相关内容
            if (this.gameState === 'levelIntro') {
                console.log('🎭 等待地狱模式介绍完成，游戏暂停中...');
            }
            return;
        }
        
        // 更新玩家
        if (window.player) {
            window.player.update(deltaTime, this.keys, this.mouse);
        }
        
        // 更新僵尸 - 添加错误处理防止技能攻击导致的崩溃
        this.zombies.forEach((zombie, index) => {
            try {
                if (zombie && typeof zombie.update === 'function') {
                    zombie.update(deltaTime, window.player);
                } else {
                    console.warn('无效的僵尸对象，移除:', zombie);
                    this.zombies.splice(index, 1);
                }
            } catch (zombieUpdateError) {
                console.error('僵尸更新错误:', zombieUpdateError);
                console.error('问题僵尸:', zombie);
                // 不移除僵尸，只记录错误以避免更严重的问题
            }
        });
        
        // 更新僵尸投射物 - 使用新的安全系统
        this.safeUpdateZombieProjectiles(deltaTime);
        
        // 定期清理和维护
        this.performMaintenance();
        
        // 更新子弹
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            const bullet = this.bullets[i];
            
            try {
                const shouldRemove = bullet.update(deltaTime) === false;
                
                // 激光束特殊处理 - 有生命周期
                if (bullet.constructor.name === 'LaserBeam') {
                    if (shouldRemove || bullet.life <= 0) {
                        this.bullets.splice(i, 1);
                    }
                } else {
                    // 普通子弹和等离子球检查边界
                    if (bullet.x < 0 || bullet.x > this.canvas.width || 
                        bullet.y < 0 || bullet.y > this.canvas.height) {
                        // 记录未命中统计
                        if (window.storageManager) {
                            window.storageManager.updateStatistics('miss');
                        }
                        this.bullets.splice(i, 1);
                    }
                }
            } catch (error) {
                // 移除有问题的子弹
                this.bullets.splice(i, 1);
            }
        }
        
        // 更新粒子效果
        this.particles.forEach((particle, index) => {
            particle.update(deltaTime);
            if (particle.life <= 0) {
                this.particles.splice(index, 1);
            }
        });
        
        // 更新道具
        this.powerUps.forEach((powerUp, index) => {
            if (!powerUp.update(deltaTime)) {
                this.powerUps.splice(index, 1);
            } else if (window.player && powerUp.collect(window.player)) {
                this.powerUps.splice(index, 1);
            }
        });
        
        // 更新浮动文字
        this.floatingTexts.forEach((text, index) => {
            if (!text.update(deltaTime)) {
                this.floatingTexts.splice(index, 1);
            }
        });
        
        // 更新Boss投射物
        this.bossProjectiles.forEach((projectile, index) => {
            if (!projectile.update(deltaTime)) {
                this.bossProjectiles.splice(index, 1);
            }
        });
        
        // 更新武器生成器
        if (window.gameManager && window.gameManager.levelManager && window.gameManager.levelManager.weaponSpawner) {
            window.gameManager.levelManager.weaponSpawner.update(deltaTime);
        }
        
        // 更新Boss
        if (this.boss) {
            this.boss.update(deltaTime, window.player);
            if (this.boss.state === 'dying' && this.boss.health <= 0) {
                this.boss = null;
            }
        }
        
        // 碰撞检测
        this.checkCollisions();
        
        // 检查游戏状态
        this.checkGameConditions();
        
        // 第9关特殊监控
        this.level9MonitorPerformance();
        
        // BOSS关卡性能优化（第10关和第20关）
        this.bossLevelPerformanceOptimization();
    }
    
    // 第9关性能监控系统
    level9MonitorPerformance() {
        try {
            const currentLevel = window.gameManager ? window.gameManager.levelManager.currentLevel : 1;
            if (currentLevel !== 9) return;
            
            // 初始化监控数据
            if (!this.level9Monitor) {
                this.level9Monitor = {
                    lastCleanupTime: Date.now(),
                    errorCount: 0,
                    projectileWarnings: 0,
                    performanceWarnings: 0
                };
            }
            
            const now = Date.now();
            
            // 每10秒进行一次深度清理（第9关专用）
            if (now - this.level9Monitor.lastCleanupTime > 10000) {
                this.level9DeepCleanup();
                this.level9Monitor.lastCleanupTime = now;
            }
            
            // 监控投射物数量
            const projectileCount = this.zombieProjectiles ? this.zombieProjectiles.length : 0;
            if (projectileCount > 8) {
                this.level9Monitor.projectileWarnings++;
                console.warn(`第9关警告：投射物数量过多 (${projectileCount})`);
                
                // 强制清理多余投射物
                if (this.zombieProjectiles && this.zombieProjectiles.length > 10) {
                    this.zombieProjectiles = this.zombieProjectiles.slice(0, 5);
                    console.warn('第9关：强制清理投射物数组');
                }
            }
            
            // 监控总对象数量
            const totalObjects = this.zombies.length + this.bullets.length + 
                                this.particles.length + projectileCount;
            if (totalObjects > 200) {
                this.level9Monitor.performanceWarnings++;
                console.warn(`第9关性能警告：对象总数过多 (${totalObjects})`);
                this.level9EmergencyCleanup();
            }
            
            // 错误统计报告
            if (this.level9Monitor.errorCount > 10) {
                console.error('第9关：错误计数过高，启动紧急保护模式');
                this.level9EmergencyMode = true;
            }
            
        } catch (monitorError) {
            console.warn('第9关监控系统错误:', monitorError);
        }
    }
    
    // 第9关深度清理系统
    level9DeepCleanup() {
        try {
            console.log('第9关：执行深度清理');
            
            // 清理无效粒子
            if (this.particles) {
                this.particles = this.particles.filter(particle => 
                    particle && typeof particle.update === 'function' && particle.life > 0
                );
            }
            
            // 清理过时的子弹
            if (this.bullets) {
                this.bullets = this.bullets.filter(bullet => 
                    bullet && bullet.x >= -100 && bullet.x <= this.canvas.width + 100 &&
                    bullet.y >= -100 && bullet.y <= this.canvas.height + 100
                );
            }
            
            // 验证僵尸数组
            if (this.zombies) {
                this.zombies = this.zombies.filter(zombie => 
                    zombie && zombie.health > 0 && typeof zombie.update === 'function'
                );
            }
            
            // 强制垃圾回收提示
            if (window.gc && typeof window.gc === 'function') {
                try {
                    window.gc();
                } catch (gcError) {
                    // 垃圾回收不可用，忽略
                }
            }
            
            console.log('第9关：深度清理完成');
            
        } catch (cleanupError) {
            console.error('第9关深度清理失败:', cleanupError);
        }
    }
    
    // 第9关紧急清理
    level9EmergencyCleanup() {
        try {
            console.warn('第9关：启动紧急清理模式');
            
            // 保留最少必要的对象
            if (this.particles && this.particles.length > 20) {
                this.particles = this.particles.slice(0, 10);
            }
            
            if (this.bullets && this.bullets.length > 30) {
                this.bullets = this.bullets.slice(0, 15);
            }
            
            if (this.zombieProjectiles && this.zombieProjectiles.length > 5) {
                this.zombieProjectiles = this.zombieProjectiles.slice(0, 3);
            }
            
            // 清空浮动文字
            this.floatingTexts = [];
            
            console.warn('第9关：紧急清理完成');
            
        } catch (emergencyError) {
            console.error('第9关紧急清理失败:', emergencyError);
            // 最后手段：清空所有数组
            this.zombieProjectiles = [];
            this.particles = [];
            this.floatingTexts = [];
        }
    }
    
    // BOSS关卡性能优化系统（第10关和第20关）
    bossLevelPerformanceOptimization() {
        try {
            const currentLevel = window.gameManager ? window.gameManager.levelManager.currentLevel : 1;
            if (currentLevel !== 10 && currentLevel !== 20) return;
            
            // 初始化BOSS关卡监控
            if (!this.bossLevelMonitor) {
                this.bossLevelMonitor = {
                    lastOptimization: Date.now(),
                    particleCleanups: 0,
                    projectileOptimizations: 0,
                    frameRateChecks: 0
                };
            }
            
            const now = Date.now();
            
            // 每5秒进行一次性能优化
            if (now - this.bossLevelMonitor.lastOptimization > 5000) {
                this.level10OptimizePerformance();
                this.bossLevelMonitor.lastOptimization = now;
            }
            
            // 监控粒子数量（BOSS技能会产生大量粒子）
            if (this.particles && this.particles.length > 150) {
                this.bossLevelMonitor.particleCleanups++;
                console.warn(`第10关：粒子数量过多 (${this.particles.length})，执行清理`);
                this.level10CleanParticles();
            }
            
            // 监控投射物复杂度（BOSS技能产生高优先级投射物）
            const projectileCount = this.zombieProjectiles ? this.zombieProjectiles.length : 0;
            if (projectileCount > 50) {
                this.bossLevelMonitor.projectileOptimizations++;
                console.warn(`第10关：投射物数量超载 (${projectileCount})`);
                this.level10OptimizeProjectiles();
            }
            
            // 帧率监控（如果可用）
            if (this.fps && this.fps < 30) {
                this.bossLevelMonitor.frameRateChecks++;
                console.warn(`第10关：帧率过低 (${this.fps}fps)，启动紧急优化`);
                this.level10EmergencyOptimization();
            }
            
        } catch (optimizationError) {
            console.warn('第10关性能优化错误:', optimizationError);
        }
    }
    
    // 第10关性能优化
    level10OptimizePerformance() {
        try {
            console.log('第10关：执行性能优化');
            
            // 优化粒子系统
            if (this.particles && this.particles.length > 100) {
                // 保留最新和最重要的粒子
                this.particles = this.particles
                    .filter(particle => particle.life > 100) // 移除即将消失的粒子
                    .slice(-100); // 只保留最新的100个
                console.log('第10关：粒子系统优化完成');
            }
            
            // 优化浮动文字
            if (this.floatingTexts && this.floatingTexts.length > 20) {
                this.floatingTexts = this.floatingTexts.slice(-15);
                console.log('第10关：浮动文字优化完成');
            }
            
            // 清理无效对象
            this.level10CleanInvalidObjects();
            
        } catch (error) {
            console.error('第10关性能优化失败:', error);
        }
    }
    
    // 第10关粒子清理
    level10CleanParticles() {
        try {
            if (!this.particles) return;
            
            const originalCount = this.particles.length;
            
            // 智能清理：保留重要粒子，移除普通粒子
            this.particles = this.particles.filter(particle => {
                // 保留BOSS相关特效
                if (particle.isBossEffect || particle.priority === 'high') {
                    return true;
                }
                // 保留生命值高的粒子
                if (particle.life > particle.maxLife * 0.7) {
                    return true;
                }
                // 移除其他粒子
                return Math.random() < 0.3; // 30%概率保留
            });
            
            const cleanedCount = originalCount - this.particles.length;
            console.log(`第10关：清理了 ${cleanedCount} 个粒子`);
            
        } catch (error) {
            console.error('第10关粒子清理失败:', error);
            // 失败时强制清理
            this.particles = this.particles ? this.particles.slice(-50) : [];
        }
    }
    
    // 第10关投射物优化
    level10OptimizeProjectiles() {
        try {
            if (!this.zombieProjectiles) return;
            
            const originalCount = this.zombieProjectiles.length;
            
            // 优先保护BOSS投射物，清理普通投射物
            const bossProjectiles = [];
            const normalProjectiles = [];
            
            this.zombieProjectiles.forEach(projectile => {
                if (projectile.isBossProjectile || projectile.priority === 'high') {
                    bossProjectiles.push(projectile);
                } else {
                    normalProjectiles.push(projectile);
                }
            });
            
            // 保留所有BOSS投射物，限制普通投射物
            const maxNormal = Math.max(10, 40 - bossProjectiles.length);
            const keepNormal = normalProjectiles.slice(-maxNormal);
            
            this.zombieProjectiles = [...bossProjectiles, ...keepNormal];
            
            const cleanedCount = originalCount - this.zombieProjectiles.length;
            console.log(`第10关：优化了 ${cleanedCount} 个投射物`);
            
        } catch (error) {
            console.error('第10关投射物优化失败:', error);
        }
    }
    
    // 第10关紧急优化
    level10EmergencyOptimization() {
        try {
            console.warn('第10关：启动紧急性能优化');
            
            // 大幅减少粒子数量
            if (this.particles && this.particles.length > 50) {
                this.particles = this.particles.slice(-30);
            }
            
            // 限制投射物数量
            if (this.zombieProjectiles && this.zombieProjectiles.length > 30) {
                // 保护BOSS投射物
                const important = this.zombieProjectiles.filter(p => 
                    p.isBossProjectile || p.priority === 'high').slice(-20);
                const normal = this.zombieProjectiles.filter(p => 
                    !p.isBossProjectile && p.priority !== 'high').slice(-10);
                this.zombieProjectiles = [...important, ...normal];
            }
            
            // 清空浮动文字
            this.floatingTexts = [];
            
            // 清理死亡的召唤物
            if (this.zombies) {
                this.zombies = this.zombies.filter(zombie => zombie.health > 0);
            }
            
            console.warn('第10关：紧急优化完成');
            
        } catch (emergencyError) {
            console.error('第10关紧急优化失败:', emergencyError);
        }
    }
    
    // 第10关清理无效对象
    level10CleanInvalidObjects() {
        try {
            // 清理无效子弹
            if (this.bullets) {
                this.bullets = this.bullets.filter(bullet => 
                    bullet && typeof bullet.update === 'function'
                );
            }
            
            // 清理无效粒子
            if (this.particles) {
                this.particles = this.particles.filter(particle => 
                    particle && typeof particle.update === 'function' && particle.life > 0
                );
            }
            
            // 清理无效投射物
            if (this.zombieProjectiles) {
                this.zombieProjectiles = this.zombieProjectiles.filter(projectile => 
                    this.isValidProjectile(projectile)
                );
            }
            
            console.log('第10关：无效对象清理完成');
            
        } catch (error) {
            console.error('第10关对象清理失败:', error);
        }
    }
    
    render() {
        // 绘制更好看的背景
        this.drawBackground();
        
        if (this.gameState === 'playing') {
            // 绘制环境细节
            this.drawEnvironmentDetails();
            
            // 绘制武器
            this.weapons.forEach(weapon => weapon.render(this.ctx));
            
            // 绘制近战武器
            this.meleeWeapons.forEach(meleeWeapon => meleeWeapon.renderDropped(this.ctx, Date.now()));
            
            // 绘制玩家
            if (window.player) {
                window.player.render(this.ctx);
            } else {
                // 调试信息
                this.ctx.fillStyle = '#FF0000';
                this.ctx.font = '20px Arial';
                this.ctx.fillText('Player not found!', 100, 100);
            }
            
            // 绘制道具
            this.powerUps.forEach(powerUp => powerUp.render(this.ctx));
            
            // 绘制僵尸
            this.zombies.forEach(zombie => zombie.render(this.ctx));
            
            // 绘制Boss
            if (this.boss) {
                this.boss.render(this.ctx);
            }
            
            // 绘制子弹
            this.bullets.forEach(bullet => bullet.render(this.ctx));
            
            // 绘制Boss投射物
            this.bossProjectiles.forEach(projectile => projectile.render(this.ctx));
            
            // 绘制僵尸投射物
            this.renderZombieProjectiles();
            
            // 绘制粒子效果
            this.particles.forEach(particle => particle.render(this.ctx));
            
            // 绘制浮动文字
            this.floatingTexts.forEach(text => text.render(this.ctx));
            
            // 绘制视觉效果
            if (window.visualEffects) {
                window.visualEffects.renderAll(this.ctx);
            }
            
            // 调试信息 - 显示僵尸数量
            this.ctx.fillStyle = '#FFFFFF';
            this.ctx.font = '16px Arial';
            this.ctx.fillText(`Zombies: ${this.zombies.length}`, 20, 30);
            this.ctx.fillText(`Game State: ${this.gameState}`, 20, 50);
            if (this.boss) {
                this.ctx.fillText(`Boss: ${this.boss.health}/${this.boss.maxHealth}`, 20, 70);
            }
        }
    }
    
    drawBackground() {
        // 创建更丰富的背景渐变
        const gradient = this.ctx.createRadialGradient(
            this.canvas.width/2, this.canvas.height/2, 0,
            this.canvas.width/2, this.canvas.height/2, Math.max(this.canvas.width, this.canvas.height)/2
        );
        gradient.addColorStop(0, '#2a3b2a');
        gradient.addColorStop(0.4, '#1f2e20');
        gradient.addColorStop(0.8, '#151a16');
        gradient.addColorStop(1, '#0d100e');
        
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制地板瓷砖 (仅在初始化时绘制一次)
        if (!this.backgroundDrawn) {
            this.drawFloorTiles();
            this.drawEnvironmentFeatures();
            this.backgroundDrawn = true;
        }
        
        // 添加动态阴影效果
        this.drawDynamicShadows();
    }
    
    drawFloorTiles() {
        // 预设的瓷砖图案
        if (!this.tilePattern) {
            this.generateTilePattern();
        }
        
        const tileSize = 40;
        
        for (let x = 0; x < this.canvas.width; x += tileSize) {
            for (let y = 0; y < this.canvas.height; y += tileSize) {
                const tileIndex = (Math.floor(x / tileSize) + Math.floor(y / tileSize)) % this.tilePattern.length;
                const tile = this.tilePattern[tileIndex];
                
                // 基础瓷砖渐变
                const tileGradient = this.ctx.createLinearGradient(x, y, x + tileSize, y + tileSize);
                tileGradient.addColorStop(0, tile.color);
                tileGradient.addColorStop(1, tile.darkColor);
                this.ctx.fillStyle = tileGradient;
                this.ctx.fillRect(x, y, tileSize, tileSize);
                
                // 瓷砖边缘和纹理
                this.ctx.strokeStyle = '#0f1a10';
                this.ctx.lineWidth = 1;
                this.ctx.strokeRect(x, y, tileSize, tileSize);
                
                // 瓷砖纹理细节
                if (tile.hasTexture) {
                    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.05)';
                    this.ctx.fillRect(x + 2, y + 2, tileSize - 4, 2);
                    this.ctx.fillRect(x + 2, y + 2, 2, tileSize - 4);
                }
                
                // 污渍和血迹
                if (tile.hasStain) {
                    const stainGradient = this.ctx.createRadialGradient(
                        x + tileSize/2, y + tileSize/2, 0,
                        x + tileSize/2, y + tileSize/2, tileSize/3
                    );
                    stainGradient.addColorStop(0, 'rgba(139, 0, 0, 0.4)');
                    stainGradient.addColorStop(1, 'rgba(139, 0, 0, 0.1)');
                    this.ctx.fillStyle = stainGradient;
                    this.ctx.fillRect(x + 6, y + 6, tileSize - 12, tileSize - 12);
                }
                
                // 裂痕
                if (tile.hasCrack) {
                    this.ctx.strokeStyle = 'rgba(0, 0, 0, 0.6)';
                    this.ctx.lineWidth = 1;
                    this.ctx.beginPath();
                    this.ctx.moveTo(x + tile.crackStart.x, y + tile.crackStart.y);
                    this.ctx.lineTo(x + tile.crackEnd.x, y + tile.crackEnd.y);
                    this.ctx.stroke();
                }
            }
        }
    }
    
    generateTilePattern() {
        this.tilePattern = [];
        for (let i = 0; i < 30; i++) {
            const baseColor = Math.random() > 0.7 ? '#2a3b2a' : '#2c3e2d';
            const darkColor = Math.random() > 0.7 ? '#1f2a20' : '#212e22';
            
            this.tilePattern.push({
                color: baseColor,
                darkColor: darkColor,
                hasStain: Math.random() > 0.85,
                hasTexture: Math.random() > 0.6,
                hasCrack: Math.random() > 0.9,
                crackStart: {
                    x: Math.random() * 40,
                    y: Math.random() * 40
                },
                crackEnd: {
                    x: Math.random() * 40,
                    y: Math.random() * 40
                }
            });
        }
    }
    
    drawEnvironmentDetails() {
        // 绘制一些环境装饰
        this.drawWalls();
        this.drawDebris();
    }
    
    drawWalls() {
        // 上墙
        this.ctx.fillStyle = '#1a1a1a';
        this.ctx.fillRect(0, 0, this.canvas.width, 20);
        
        // 下墙
        this.ctx.fillRect(0, this.canvas.height - 20, this.canvas.width, 20);
        
        // 左墙
        this.ctx.fillRect(0, 0, 20, this.canvas.height);
        
        // 右墙
        this.ctx.fillRect(this.canvas.width - 20, 0, 20, this.canvas.height);
        
        // 墙面细节
        this.ctx.fillStyle = '#2a2a2a';
        for (let i = 0; i < this.canvas.width; i += 40) {
            this.ctx.fillRect(i, 5, 30, 10);
            this.ctx.fillRect(i, this.canvas.height - 15, 30, 10);
        }
    }
    
    drawDebris() {
        // 预设的碎片位置
        if (!this.debrisPositions) {
            this.debrisPositions = [];
            for (let i = 0; i < 25; i++) {
                this.debrisPositions.push({
                    x: Math.random() * (this.canvas.width - 40) + 20,
                    y: Math.random() * (this.canvas.height - 40) + 20,
                    size: Math.random() * 12 + 6,
                    type: Math.floor(Math.random() * 3), // 0: 石头, 1: 木头, 2: 金属
                    rotation: Math.random() * Math.PI * 2
                });
            }
        }
        
        this.debrisPositions.forEach(debris => {
            this.ctx.save();
            this.ctx.translate(debris.x + debris.size/2, debris.y + debris.size/2);
            this.ctx.rotate(debris.rotation);
            
            // 根据类型绘制不同的碎片
            if (debris.type === 0) {
                // 石头碎片
                this.ctx.fillStyle = '#4a4a4a';
                this.ctx.fillRect(-debris.size/2, -debris.size/2, debris.size, debris.size);
                this.ctx.fillStyle = '#3a3a3a';
                this.ctx.fillRect(-debris.size/2 + 1, -debris.size/2 + 1, debris.size - 2, debris.size - 2);
            } else if (debris.type === 1) {
                // 木头碎片
                this.ctx.fillStyle = '#8B4513';
                this.ctx.fillRect(-debris.size/2, -debris.size/2, debris.size, debris.size * 0.3);
                this.ctx.fillRect(-debris.size/2, -debris.size/2 + debris.size * 0.7, debris.size, debris.size * 0.3);
            } else {
                // 金属碎片
                this.ctx.fillStyle = '#696969';
                this.ctx.fillRect(-debris.size/2, -debris.size/2, debris.size, debris.size);
                this.ctx.fillStyle = '#808080';
                this.ctx.fillRect(-debris.size/2 + 2, -debris.size/2 + 2, debris.size - 4, 1);
            }
            
            this.ctx.restore();
        });
    }
    
    // 新增：环境特性
    drawEnvironmentFeatures() {
        this.generateEnvironmentFeatures();
        this.drawPillars();
        // this.drawBloodStains(); // 禁用血迹绘制
        this.drawBrokenGlass();
        this.drawObstacles();
        this.drawApocalypseDecor();
    }
    
    generateEnvironmentFeatures() {
        if (!this.environmentFeatures) {
            this.environmentFeatures = {
                pillars: [],
                bloodStains: [],
                brokenGlass: [],
                obstacles: [],
                apocalypseDecor: []
            };
            
            // 生成柱子
            for (let i = 0; i < 4; i++) {
                this.environmentFeatures.pillars.push({
                    x: Math.random() * (this.canvas.width - 200) + 100,
                    y: Math.random() * (this.canvas.height - 200) + 100,
                    width: 30 + Math.random() * 20,
                    height: 80 + Math.random() * 40
                });
            }
            
            // 生成血迹（增加数量和多样性） - 血迹效果已禁用
            // for (let i = 0; i < 25; i++) {
            //     this.environmentFeatures.bloodStains.push({
            //         x: Math.random() * this.canvas.width,
            //         y: Math.random() * this.canvas.height,
            //         size: Math.random() * 40 + 15,
            //         intensity: Math.random() * 0.8 + 0.2,
            //         type: Math.floor(Math.random() * 3) // 0: 圆形, 1: 溅射, 2: 拖痕
            //     });
            // }
            
            // 生成碎玻璃
            for (let i = 0; i < 30; i++) {
                this.environmentFeatures.brokenGlass.push({
                    x: Math.random() * this.canvas.width,
                    y: Math.random() * this.canvas.height,
                    size: Math.random() * 12 + 4,
                    angle: Math.random() * Math.PI * 2
                });
            }
            
            // 生成障碍物（桌子、书架、垃圾桶等）
            for (let i = 0; i < 8; i++) {
                const obstacleType = Math.floor(Math.random() * 4);
                this.environmentFeatures.obstacles.push({
                    x: Math.random() * (this.canvas.width - 120) + 60,
                    y: Math.random() * (this.canvas.height - 120) + 60,
                    type: obstacleType, // 0: 桌子, 1: 书架, 2: 垃圾桶, 3: 柜子
                    rotation: Math.random() * Math.PI * 2,
                    damaged: Math.random() > 0.3
                });
            }
            
            // 生成末日装饰
            for (let i = 0; i < 15; i++) {
                const decorType = Math.floor(Math.random() * 5);
                this.environmentFeatures.apocalypseDecor.push({
                    x: Math.random() * this.canvas.width,
                    y: Math.random() * this.canvas.height,
                    type: decorType, // 0: 骨头, 1: 破损海报, 2: 弹壳, 3: 医疗包, 4: 尸体轮廓
                    size: Math.random() * 20 + 10,
                    angle: Math.random() * Math.PI * 2
                });
            }
        }
    }
    
    drawPillars() {
        this.environmentFeatures.pillars.forEach(pillar => {
            // 柱子主体
            const gradient = this.ctx.createLinearGradient(
                pillar.x, pillar.y, 
                pillar.x + pillar.width, pillar.y + pillar.height
            );
            gradient.addColorStop(0, '#4a4a4a');
            gradient.addColorStop(0.5, '#3a3a3a');
            gradient.addColorStop(1, '#2a2a2a');
            
            this.ctx.fillStyle = gradient;
            this.ctx.fillRect(pillar.x, pillar.y, pillar.width, pillar.height);
            
            // 柱子阴影
            this.ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
            this.ctx.fillRect(pillar.x + pillar.width, pillar.y + 5, 8, pillar.height);
            this.ctx.fillRect(pillar.x + 5, pillar.y + pillar.height, pillar.width, 8);
        });
    }
    
    drawBloodStains() {
        this.environmentFeatures.bloodStains.forEach(stain => {
            if (stain.type === 0) {
                // 圆形血迹
                const gradient = this.ctx.createRadialGradient(
                    stain.x, stain.y, 0,
                    stain.x, stain.y, stain.size
                );
                gradient.addColorStop(0, `rgba(139, 0, 0, ${stain.intensity})`);
                gradient.addColorStop(0.7, `rgba(139, 0, 0, ${stain.intensity * 0.5})`);
                gradient.addColorStop(1, 'rgba(139, 0, 0, 0)');
                
                this.ctx.fillStyle = gradient;
                this.ctx.beginPath();
                this.ctx.arc(stain.x, stain.y, stain.size, 0, Math.PI * 2);
                this.ctx.fill();
            } else if (stain.type === 1) {
                // 溅射血迹
                this.ctx.fillStyle = `rgba(139, 0, 0, ${stain.intensity})`;
                for (let i = 0; i < 8; i++) {
                    const angle = (Math.PI * 2 * i) / 8;
                    const distance = stain.size * (0.3 + Math.random() * 0.7);
                    const x = stain.x + Math.cos(angle) * distance;
                    const y = stain.y + Math.sin(angle) * distance;
                    const size = Math.random() * 6 + 2;
                    
                    this.ctx.beginPath();
                    this.ctx.arc(x, y, size, 0, Math.PI * 2);
                    this.ctx.fill();
                }
            } else {
                // 拖痕血迹
                this.ctx.strokeStyle = `rgba(139, 0, 0, ${stain.intensity})`;
                this.ctx.lineWidth = stain.size / 3;
                this.ctx.lineCap = 'round';
                this.ctx.beginPath();
                this.ctx.moveTo(stain.x, stain.y);
                this.ctx.lineTo(stain.x + stain.size, stain.y + stain.size * 0.3);
                this.ctx.stroke();
            }
        });
    }
    
    drawBrokenGlass() {
        this.environmentFeatures.brokenGlass.forEach(glass => {
            this.ctx.save();
            this.ctx.translate(glass.x, glass.y);
            this.ctx.rotate(glass.angle);
            
            // 玻璃片
            this.ctx.fillStyle = 'rgba(200, 220, 255, 0.6)';
            this.ctx.fillRect(-glass.size/2, -1, glass.size, 2);
            this.ctx.fillRect(-1, -glass.size/2, 2, glass.size);
            
            // 玻璃高光
            this.ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
            this.ctx.fillRect(-glass.size/4, -0.5, glass.size/2, 1);
            
            this.ctx.restore();
        });
    }
    
    // 新增：动态阴影效果
    drawDynamicShadows() {
        if (!window.player) return;
        
        // 玩家周围的动态光源效果
        const gradient = this.ctx.createRadialGradient(
            window.player.x, window.player.y, 0,
            window.player.x, window.player.y, 150
        );
        gradient.addColorStop(0, 'rgba(255, 255, 200, 0.1)');
        gradient.addColorStop(0.5, 'rgba(255, 255, 200, 0.05)');
        gradient.addColorStop(1, 'rgba(0, 0, 0, 0.2)');
        
        this.ctx.fillStyle = gradient;
        this.ctx.beginPath();
        this.ctx.arc(window.player.x, window.player.y, 150, 0, Math.PI * 2);
        this.ctx.fill();
    }
    
    // 新增：障碍物绘制
    drawObstacles() {
        this.environmentFeatures.obstacles.forEach(obstacle => {
            this.ctx.save();
            this.ctx.translate(obstacle.x + 30, obstacle.y + 30);
            this.ctx.rotate(obstacle.rotation);
            
            if (obstacle.type === 0) {
                // 翻倒的桌子
                this.drawTable(obstacle.damaged);
            } else if (obstacle.type === 1) {
                // 倒塌的书架
                this.drawBookshelf(obstacle.damaged);
            } else if (obstacle.type === 2) {
                // 垃圾桶
                this.drawTrashCan(obstacle.damaged);
            } else {
                // 破损柜子
                this.drawCabinet(obstacle.damaged);
            }
            
            this.ctx.restore();
        });
    }
    
    drawTable(damaged) {
        // 桌面
        this.ctx.fillStyle = damaged ? '#8B4513' : '#A0522D';
        this.ctx.fillRect(-25, -5, 50, 10);
        
        // 桌腿（部分断裂）
        this.ctx.fillStyle = '#654321';
        if (!damaged || Math.random() > 0.5) this.ctx.fillRect(-20, 5, 4, 15);
        if (!damaged || Math.random() > 0.5) this.ctx.fillRect(16, 5, 4, 15);
        if (!damaged || Math.random() > 0.5) this.ctx.fillRect(-20, -20, 4, 15);
        if (!damaged || Math.random() > 0.5) this.ctx.fillRect(16, -20, 4, 15);
        
        if (damaged) {
            // 破损效果
            this.ctx.strokeStyle = '#654321';
            this.ctx.lineWidth = 2;
            this.ctx.beginPath();
            this.ctx.moveTo(-25, -5);
            this.ctx.lineTo(25, 5);
            this.ctx.stroke();
        }
    }
    
    drawBookshelf(damaged) {
        // 书架主体
        this.ctx.fillStyle = damaged ? '#8B4513' : '#A0522D';
        this.ctx.fillRect(-20, -30, 40, 60);
        
        // 书架隔板
        for (let i = -20; i <= 20; i += 20) {
            this.ctx.fillStyle = '#654321';
            this.ctx.fillRect(-18, i, 36, 3);
        }
        
        // 书本
        if (!damaged) {
            const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4'];
            for (let shelf = -25; shelf <= 15; shelf += 20) {
                for (let book = -15; book <= 10; book += 5) {
                    this.ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
                    this.ctx.fillRect(book, shelf, 4, 15);
                }
            }
        } else {
            // 散落的书本
            for (let i = 0; i < 8; i++) {
                this.ctx.fillStyle = '#FF6B6B';
                const x = -30 + Math.random() * 60;
                const y = 30 + Math.random() * 20;
                this.ctx.fillRect(x, y, 6, 2);
            }
        }
    }
    
    drawTrashCan(damaged) {
        // 垃圾桶主体
        this.ctx.fillStyle = damaged ? '#666666' : '#808080';
        this.ctx.fillRect(-12, -15, 24, 30);
        
        // 盖子
        if (!damaged) {
            this.ctx.fillStyle = '#696969';
            this.ctx.fillRect(-14, -18, 28, 6);
        }
        
        // 垃圾（如果损坏则散落）
        if (damaged) {
            for (let i = 0; i < 6; i++) {
                this.ctx.fillStyle = ['#8B4513', '#654321', '#FFD700'][Math.floor(Math.random() * 3)];
                const x = -20 + Math.random() * 40;
                const y = 15 + Math.random() * 15;
                this.ctx.fillRect(x, y, 4, 4);
            }
        }
    }
    
    drawCabinet(damaged) {
        // 柜子主体
        this.ctx.fillStyle = damaged ? '#8B4513' : '#A0522D';
        this.ctx.fillRect(-25, -25, 50, 50);
        
        // 柜门
        if (!damaged) {
            this.ctx.strokeStyle = '#654321';
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(-23, -23, 23, 46);
            this.ctx.strokeRect(0, -23, 23, 46);
            
            // 门把手
            this.ctx.fillStyle = '#B8860B';
            this.ctx.fillRect(-5, 0, 3, 3);
            this.ctx.fillRect(17, 0, 3, 3);
        } else {
            // 破损的门
            this.ctx.strokeStyle = '#654321';
            this.ctx.lineWidth = 2;
            this.ctx.beginPath();
            this.ctx.moveTo(-23, -23);
            this.ctx.lineTo(-10, -10);
            this.ctx.lineTo(0, -23);
            this.ctx.stroke();
        }
    }
    
    // 新增：末日装饰绘制
    drawApocalypseDecor() {
        this.environmentFeatures.apocalypseDecor.forEach(decor => {
            this.ctx.save();
            this.ctx.translate(decor.x, decor.y);
            this.ctx.rotate(decor.angle);
            
            if (decor.type === 0) {
                // 骨头
                this.drawBone(decor.size);
            } else if (decor.type === 1) {
                // 破损海报
                this.drawBrokenPoster(decor.size);
            } else if (decor.type === 2) {
                // 弹壳
                this.drawBulletCasing(decor.size);
            } else if (decor.type === 3) {
                // 医疗包
                this.drawMedKit(decor.size);
            } else {
                // 尸体轮廓
                this.drawBodyOutline(decor.size);
            }
            
            this.ctx.restore();
        });
    }
    
    drawBone(size) {
        this.ctx.fillStyle = '#F5F5DC';
        this.ctx.fillRect(-size/2, -2, size, 4);
        this.ctx.fillRect(-size/2 - 3, -4, 6, 8);
        this.ctx.fillRect(size/2 - 3, -4, 6, 8);
    }
    
    drawBrokenPoster(size) {
        this.ctx.fillStyle = '#D2B48C';
        this.ctx.fillRect(-size/2, -size/2, size, size);
        
        // 撕裂边缘
        this.ctx.strokeStyle = '#A0522D';
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.moveTo(-size/2, -size/2);
        this.ctx.lineTo(size/4, size/4);
        this.ctx.lineTo(size/2, -size/2);
        this.ctx.stroke();
    }
    
    drawBulletCasing(size) {
        this.ctx.fillStyle = '#DAA520';
        this.ctx.fillRect(-2, -size/4, 4, size/2);
        this.ctx.fillStyle = '#B8860B';
        this.ctx.fillRect(-2, -size/4, 4, 2);
    }
    
    drawMedKit(size) {
        this.ctx.fillStyle = '#FF6B6B';
        this.ctx.fillRect(-size/2, -size/3, size, size*2/3);
        
        // 红十字
        this.ctx.fillStyle = '#FFFFFF';
        this.ctx.fillRect(-2, -size/4, 4, size/2);
        this.ctx.fillRect(-size/4, -2, size/2, 4);
    }
    
    drawBodyOutline(size) {
        this.ctx.strokeStyle = 'rgba(139, 0, 0, 0.6)';
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        
        // 简单的人形轮廓
        this.ctx.arc(0, -size/2, size/4, 0, Math.PI * 2); // 头
        this.ctx.moveTo(0, -size/4);
        this.ctx.lineTo(0, size/4); // 身体
        this.ctx.moveTo(0, -size/6);
        this.ctx.lineTo(-size/3, size/6); // 左臂
        this.ctx.moveTo(0, -size/6);
        this.ctx.lineTo(size/3, size/6); // 右臂
        this.ctx.moveTo(0, size/4);
        this.ctx.lineTo(-size/4, size/2); // 左腿
        this.ctx.moveTo(0, size/4);
        this.ctx.lineTo(size/4, size/2); // 右腿
        
        this.ctx.stroke();
    }
    
    drawGrid() {
        this.ctx.strokeStyle = '#1a2b1d';
        this.ctx.lineWidth = 1;
        
        const gridSize = 32;
        
        for (let x = 0; x < this.canvas.width; x += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvas.height);
            this.ctx.stroke();
        }
        
        for (let y = 0; y < this.canvas.height; y += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvas.width, y);
            this.ctx.stroke();
        }
    }
    
    checkCollisions() {
        // 子弹与僵尸碰撞
        for (let bulletIndex = this.bullets.length - 1; bulletIndex >= 0; bulletIndex--) {
            const bullet = this.bullets[bulletIndex];
            
            // 激光束特殊处理
            if (bullet.constructor.name === 'LaserBeam') {
                this.handleLaserCollisions(bullet);
                continue;
            }
            
            for (let zombieIndex = this.zombies.length - 1; zombieIndex >= 0; zombieIndex--) {
                const zombie = this.zombies[zombieIndex];
                
                if (this.isColliding(bullet, zombie)) {
                    // 创建血溅效果 - 已禁用
                    // this.createBloodSplash(zombie.x, zombie.y);
                    
                    // 伤害僵尸
                    zombie.takeDamage(bullet.damage);
                    
                    // 移除子弹
                    this.bullets.splice(bulletIndex, 1);
                    
                    // 记录命中统计
                    if (window.storageManager) {
                        window.storageManager.updateStatistics('hit');
                    }
                    
                    // 如果僵尸死亡，移除它
                    if (zombie.health <= 0) {
                        this.zombies.splice(zombieIndex, 1);
                        
                        // 增加分数和统计
                        if (window.gameManager) {
                            window.gameManager.addScore(10);
                        }
                        
                        if (window.storageManager) {
                            window.storageManager.updateStatistics('zombieKilled', 1, zombie.type);
                        }
                        
                        // 添加货币奖励
                        if (window.roguelikeSystem) {
                            const coinReward = this.calculateCoinReward(zombie.type);
                            window.roguelikeSystem.addCurrency(coinReward);
                        }
                        
                        // 添加经验值奖励
                        if (window.weaponEnhancement) {
                            const expReward = this.calculateExpReward(zombie.type);
                            window.weaponEnhancement.addExperience(expReward);
                            
                            // 追踪武器使用统计
                            if (window.player && window.player.currentWeapon) {
                                window.weaponEnhancement.trackWeaponUsage(
                                    window.player.currentWeapon.type, 
                                    'kills', 
                                    1
                                );
                            }
                        }
                        
                        // 检查成就
                        if (window.achievementSystem) {
                            window.achievementSystem.checkAchievements();
                        }
                        
                        // 触发视觉效果
                        if (window.visualEffects) {
                            // 发送自定义事件
                            const event = new CustomEvent('enemyKilled', {
                                detail: {
                                    x: zombie.x,
                                    y: zombie.y,
                                    damage: bullet.damage,
                                    isCritical: this.isCriticalHit(bullet)
                                }
                            });
                            document.dispatchEvent(event);
                        }
                    }
                    
                    break; // 子弹击中一个僵尸后消失
                }
            }
        }
        
        // 子弹与Boss碰撞
        if (this.boss && this.boss.health > 0) {
            for (let bulletIndex = this.bullets.length - 1; bulletIndex >= 0; bulletIndex--) {
                const bullet = this.bullets[bulletIndex];
                
                if (this.isColliding(bullet, this.boss)) {
                    // 创建血溅效果
                    // this.createBloodSplash(this.boss.x, this.boss.y); // 禁用血迹效果
                    
                    // 伤害Boss，确保有默认伤害值
                    const damage = bullet.damage || 10;
                    this.boss.takeDamage(damage);
                    
                    // 移除子弹
                    this.bullets.splice(bulletIndex, 1);
                    
                    // 记录命中统计
                    if (window.storageManager) {
                        window.storageManager.updateStatistics('hit');
                    }
                    
                    // 如果Boss死亡
                    if (this.boss.health <= 0 && this.boss.state !== 'dying') {
                        // 增加分数
                        if (window.gameManager) {
                            window.gameManager.addScore(500); // Boss给更多分数
                        }
                        
                        // 记录Boss击杀统计
                        if (window.storageManager) {
                            window.storageManager.updateStatistics('bossKilled');
                        }
                    }
                    
                    break; // 子弹击中Boss后消失
                }
            }
        }
        
        // 僵尸与玩家碰撞
        if (window.player) {
            this.zombies.forEach(zombie => {
                if (this.isColliding(zombie, window.player)) {
                    if (zombie.canAttack()) {
                        window.player.takeDamage(zombie.damage);
                        zombie.lastAttackTime = Date.now();
                        
                        // 创建伤害效果
                        // this.createDamageEffect(window.player.x, window.player.y); // 禁用伤害效果
                        
                        // 触发玩家受伤视觉效果
                        if (window.visualEffects) {
                            const event = new CustomEvent('playerHit', {
                                detail: {
                                    x: window.player.x,
                                    y: window.player.y,
                                    damage: zombie.damage
                                }
                            });
                            document.dispatchEvent(event);
                        }
                    }
                }
            });
        }
    }
    
    isColliding(obj1, obj2) {
        const distance = Math.sqrt(
            Math.pow(obj1.x - obj2.x, 2) + Math.pow(obj1.y - obj2.y, 2)
        );
        return distance < (obj1.radius || 16) + (obj2.radius || 16);
    }
    
    // 激光束碰撞检测
    handleLaserCollisions(laser) {
        try {
            if (!laser) {
                return;
            }
            
            // 激光与僵尸碰撞
            if (this.zombies && Array.isArray(this.zombies)) {
                for (let zombieIndex = this.zombies.length - 1; zombieIndex >= 0; zombieIndex--) {
                    const zombie = this.zombies[zombieIndex];
                    
                    if (!zombie || typeof zombie.takeDamage !== 'function') {
                        continue;
                    }
                    
                    if (this.isLaserHittingZombie(laser, zombie)) {
                        // 创建激光击中特效
                        this.createLaserHitEffect(zombie.x, zombie.y);
                        
                        // 伤害僵尸
                        zombie.takeDamage(laser.damage || 45);
                        
                        // 记录命中统计
                        if (window.storageManager) {
                            window.storageManager.updateStatistics('hit');
                        }
                        
                        // 如果僵尸死亡，移除它
                        if (zombie.health <= 0) {
                            this.zombies.splice(zombieIndex, 1);
                            
                            // 增加分数和统计
                            if (window.gameManager) {
                                window.gameManager.addScore(10);
                            }
                            
                            if (window.storageManager) {
                                window.storageManager.updateStatistics('zombieKilled', 1, zombie.type);
                            }
                            
                            // 检查成就
                            if (window.achievementSystem) {
                                window.achievementSystem.checkAchievements();
                            }
                            
                            // 触发视觉效果
                            this.createDeathEffect(zombie.x, zombie.y);
                        }
                    }
                }
            }
            
            // 激光与BOSS碰撞
            if (this.boss && this.boss.health > 0) {
                if (this.isLaserHittingBoss(laser, this.boss)) {
                    // 创建激光击中特效
                    this.createLaserHitEffect(this.boss.x, this.boss.y);
                    
                    // 伤害BOSS
                    const damage = laser.damage || 45;
                    this.boss.takeDamage(damage);
                    
                    // 记录命中统计
                    if (window.storageManager) {
                        window.storageManager.updateStatistics('hit');
                    }
                }
            }
            
        } catch (error) {
            // 静默处理错误
        }
    }
    
    // 检查激光是否击中BOSS
    isLaserHittingBoss(laser, boss) {
        try {
            // 安全检查
            if (!laser || !boss || !laser.startX || !laser.startY || !laser.endX || !laser.endY) {
                return false;
            }
            
            if (typeof boss.x !== 'number' || typeof boss.y !== 'number') {
                return false;
            }
            
            // 计算点到直线的距离
            const A = laser.endY - laser.startY;
            const B = laser.startX - laser.endX;
            const C = laser.endX * laser.startY - laser.startX * laser.endY;
            
            // 防止除以零
            const denominator = Math.sqrt(A * A + B * B);
            if (denominator === 0) {
                return false;
            }
            
            const distance = Math.abs(A * boss.x + B * boss.y + C) / denominator;
            
            // 获取BOSS半径，提供默认值
            const bossRadius = boss.radius || boss.size || 50;
            const laserWidth = laser.width || 4;
            
            // 检查BOSS是否在激光路径上
            if (distance <= bossRadius + laserWidth / 2) {
                // 检查BOSS是否在激光射程内
                const projectionX = boss.x - laser.startX;
                const projectionY = boss.y - laser.startY;
                const dotProduct = projectionX * laser.dirX + projectionY * laser.dirY;
                
                return dotProduct >= 0 && dotProduct <= laser.range;
            }
            
            return false;
        } catch (error) {
            return false;
        }
    }
    
    // 检查激光是否击中僵尸
    isLaserHittingZombie(laser, zombie) {
        try {
            // 安全检查
            if (!laser || !zombie || !laser.startX || !laser.startY || !laser.endX || !laser.endY) {
                return false;
            }
            
            if (typeof zombie.x !== 'number' || typeof zombie.y !== 'number') {
                return false;
            }
            
            // 计算点到直线的距离
            const A = laser.endY - laser.startY;
            const B = laser.startX - laser.endX;
            const C = laser.endX * laser.startY - laser.startX * laser.endY;
            
            // 防止除以零
            const denominator = Math.sqrt(A * A + B * B);
            if (denominator === 0) {
                return false; // 激光长度为0，无法击中
            }
            
            const distance = Math.abs(A * zombie.x + B * zombie.y + C) / denominator;
            
            // 获取僵尸半径，提供默认值
            const zombieRadius = zombie.radius || 14;
            const laserWidth = laser.width || 4;
            
            // 检查僵尸是否在激光路径上
            if (distance <= zombieRadius + laserWidth / 2) {
                // 检查僵尸是否在激光射程内
                const projectionX = zombie.x - laser.startX;
                const projectionY = zombie.y - laser.startY;
                const dotProduct = projectionX * laser.dirX + projectionY * laser.dirY;
                
                return dotProduct >= 0 && dotProduct <= laser.range;
            }
            
            return false;
        } catch (error) {
            return false;
        }
    }
    
    // 创建激光击中特效
    createLaserHitEffect(x, y) {
        try {
            if (typeof x !== 'number' || typeof y !== 'number') {
                return;
            }
            
            // 激光击中的电火花效果
            for (let i = 0; i < 12; i++) {
                this.particles.push(new Particle(
                    x, y,
                    (Math.random() - 0.5) * 150,
                    (Math.random() - 0.5) * 150,
                    '#00FFFF',
                    300
                ));
            }
            
            // 白色闪光效果
            for (let i = 0; i < 6; i++) {
                this.particles.push(new Particle(
                    x, y,
                    (Math.random() - 0.5) * 80,
                    (Math.random() - 0.5) * 80,
                    '#FFFFFF',
                    200
                ));
            }
        } catch (error) {
            // 静默处理错误
        }
    }
    
    createBloodSplash(x, y) {
        // 血迹效果已禁用
        return;
    }
    
    createDamageEffect(x, y) {
        // 伤害效果已禁用
        return;
    }
    
    // 检查是否是暴击
    isCriticalHit(bullet) {
        if (window.roguelikeSystem) {
            const critChance = window.roguelikeSystem.activeEffects.criticalChance;
            return Math.random() < critChance;
        }
        return false;
    }
    
    // 计算货币奖励
    calculateCoinReward(zombieType) {
        const baseRewards = {
            'normal': 1,
            'fast': 2,
            'tank': 3,
            'spitter': 2
        };
        
        let reward = baseRewards[zombieType] || 1;
        
        // 幸运效果加成
        if (window.roguelikeSystem && window.roguelikeSystem.activeEffects.luckMultiplier) {
            reward *= window.roguelikeSystem.activeEffects.luckMultiplier;
        }
        
        return Math.floor(reward);
    }
    
    // 计算经验值奖励
    calculateExpReward(zombieType) {
        const baseExpRewards = {
            'normal': 10,
            'fast': 15,
            'tank': 25,
            'spitter': 20
        };
        
        let exp = baseExpRewards[zombieType] || 10;
        
        // 技能效果加成
        if (window.weaponEnhancement && window.weaponEnhancement.activeSkillEffects) {
            const effects = window.weaponEnhancement.activeSkillEffects;
            if (effects.expMultiplier) {
                exp *= effects.expMultiplier;
            }
        }
        
        return Math.floor(exp);
    }
    
    checkGameConditions() {
        // 检查玩家是否死亡
        if (window.player && window.player.health <= 0) {
            this.gameState = 'gameOver';
            this.showGameOverMenu();
            return;
        }
        
        // 检查是否完成关卡
        const levelComplete = this.checkLevelComplete();
        if (levelComplete && this.gameState === 'playing' && window.gameManager && window.gameManager.levelManager.isLevelActive) {
            this.gameState = 'levelComplete';
            
            // 完成关卡
            const levelResult = window.gameManager.levelManager.completeLevel();
            console.log('关卡完成:', levelResult);
            
            this.showLevelCompleteMenu();
        }
    }
    
    checkLevelComplete() {
        const currentLevel = window.gameManager ? window.gameManager.levelManager.currentLevel : 1;
        
        if (currentLevel === 10 || currentLevel === 20) {
            // 第10关和第20关需要击败Boss
            return !this.boss || (this.boss.health <= 0);
        } else {
            // 其他关卡需要清除所有僵尸
            return this.zombies.length === 0;
        }
    }
    
    showGameOverMenu() {
        // 游戏结束时停止生命恢复循环
        if (window.newSkillTree && typeof window.newSkillTree.stopSkillEffectLoop === 'function') {
            window.newSkillTree.stopSkillEffectLoop();
        } else if (window.newSkillTreeSystem && typeof window.newSkillTreeSystem.stopSkillEffectLoop === 'function') {
            window.newSkillTreeSystem.stopSkillEffectLoop();
        }
        
        document.getElementById('gameOverMenu').classList.remove('hidden');
        document.getElementById('finalScore').textContent = 
            `最终分数: ${window.gameManager ? window.gameManager.score : 0}`;
    }
    
    showLevelCompleteMenu() {
        document.getElementById('levelCompleteMenu').classList.remove('hidden');
        document.getElementById('levelScore').textContent = 
            `本关分数: ${window.gameManager ? window.gameManager.getLevelScore() : 0}`;
    }
    
    // 新的安全投射物更新系统
    safeUpdateZombieProjectiles(deltaTime) {
        try {
            // 第9关超级安全模式
            const currentLevel = window.gameManager ? window.gameManager.levelManager.currentLevel : 1;
            if (currentLevel === 9) {
                return this.level9UltraSafeProjectileUpdate(deltaTime);
            }
            
            // 确保数组安全
            this.ensureProjectileArrays();
            
            if (!this.zombieProjectiles || this.zombieProjectiles.length === 0) {
                return; // 没有投射物，直接返回
            }
            
            // 安全的反向遍历
            for (let i = this.zombieProjectiles.length - 1; i >= 0; i--) {
                const projectile = this.zombieProjectiles[i];
                
                // 验证投射物完整性
                if (!this.isValidProjectile(projectile)) {
                    this.removeProjectileAt(i, '数据无效');
                    continue;
                }
                
                // 更新投射物位置
                if (!this.updateProjectilePosition(projectile, deltaTime)) {
                    this.removeProjectileAt(i, '位置更新失败');
                    continue;
                }
                
                // 检查生命值和边界
                if (this.shouldRemoveProjectile(projectile)) {
                    this.removeProjectileAt(i, '生命耗尽或超出边界');
                    continue;
                }
                
                // 检查与玩家碰撞
                if (this.checkProjectilePlayerCollision(projectile)) {
                    this.removeProjectileAt(i, '命中玩家');
                    continue;
                }
            }
            
        } catch (updateError) {
            console.error('投射物更新系统错误:', updateError);
            console.error('错误堆栈:', updateError.stack);
            
            // 紧急情况：清空投射物数组
            console.warn('紧急重置僵尸投射物数组');
            this.zombieProjectiles = [];
        }
    }
    
    // 第9关专用超级安全投射物更新系统
    level9UltraSafeProjectileUpdate(deltaTime) {
        try {
            // 多重安全检查
            if (!this.zombieProjectiles) {
                this.zombieProjectiles = [];
                return;
            }
            
            // 强制限制投射物数量（第9关特别保守）
            if (this.zombieProjectiles.length > 6) {
                console.warn('第9关：投射物数量超限，清理多余投射物');
                this.zombieProjectiles = this.zombieProjectiles.slice(-6); // 只保留最新的6个
            }
            
            // 使用极其安全的遍历方式
            const validProjectiles = [];
            
            for (let i = 0; i < this.zombieProjectiles.length; i++) {
                try {
                    const projectile = this.zombieProjectiles[i];
                    
                    // 第一轮检查：基础数据验证
                    if (!this.level9ValidateProjectile(projectile)) {
                        continue; // 跳过无效投射物
                    }
                    
                    // 第二轮检查：位置更新
                    if (!this.level9UpdateProjectilePosition(projectile, deltaTime)) {
                        continue; // 跳过更新失败的投射物
                    }
                    
                    // 第三轮检查：边界和生命值
                    if (this.level9ShouldRemoveProjectile(projectile)) {
                        continue; // 跳过需要移除的投射物
                    }
                    
                    // 第四轮检查：碰撞检测
                    if (this.level9CheckPlayerCollision(projectile)) {
                        continue; // 跳过已碰撞的投射物
                    }
                    
                    // 通过所有检查，投射物有效
                    validProjectiles.push(projectile);
                    
                } catch (singleProjectileError) {
                    console.warn('第9关：单个投射物处理错误，跳过:', singleProjectileError.message);
                    continue; // 跳过有问题的投射物
                }
            }
            
            // 安全替换投射物数组
            this.zombieProjectiles = validProjectiles;
            
        } catch (level9Error) {
            console.error('第9关投射物系统严重错误:', level9Error);
            console.error('错误堆栈:', level9Error.stack);
            
            // 第9关紧急清理
            this.zombieProjectiles = [];
            console.warn('第9关：紧急清空所有投射物');
            
            // 记录错误到调试面板
            if (window.debugLog) {
                window.debugLog('第9关投射物系统错误，已紧急清理');
            }
        }
    }
    
    // 第9关专用投射物验证
    level9ValidateProjectile(projectile) {
        if (!projectile) return false;
        if (typeof projectile.x !== 'number' || isNaN(projectile.x) || !isFinite(projectile.x)) return false;
        if (typeof projectile.y !== 'number' || isNaN(projectile.y) || !isFinite(projectile.y)) return false;
        if (typeof projectile.vx !== 'number' || isNaN(projectile.vx) || !isFinite(projectile.vx)) return false;
        if (typeof projectile.vy !== 'number' || isNaN(projectile.vy) || !isFinite(projectile.vy)) return false;
        if (typeof projectile.life !== 'number' || isNaN(projectile.life) || !isFinite(projectile.life)) return false;
        
        // 检查数值范围
        if (Math.abs(projectile.x) > 5000 || Math.abs(projectile.y) > 5000) return false;
        if (Math.abs(projectile.vx) > 1000 || Math.abs(projectile.vy) > 1000) return false;
        
        return true;
    }
    
    // 第9关专用位置更新
    level9UpdateProjectilePosition(projectile, deltaTime) {
        try {
            const timeStep = Math.min(deltaTime / 1000, 0.1); // 限制时间步长
            
            const newX = projectile.x + projectile.vx * timeStep;
            const newY = projectile.y + projectile.vy * timeStep;
            const newLife = projectile.life - deltaTime;
            
            // 验证新值
            if (isNaN(newX) || isNaN(newY) || isNaN(newLife) || 
                !isFinite(newX) || !isFinite(newY) || !isFinite(newLife)) {
                return false;
            }
            
            projectile.x = newX;
            projectile.y = newY;
            projectile.life = newLife;
            
            return true;
        } catch (error) {
            return false;
        }
    }
    
    // 第9关专用移除检查
    level9ShouldRemoveProjectile(projectile) {
        const margin = 50; // 更小的边界缓冲区
        
        return projectile.life <= 0 || 
               projectile.x < -margin || 
               projectile.x > this.canvas.width + margin ||
               projectile.y < -margin || 
               projectile.y > this.canvas.height + margin;
    }
    
    // 第9关专用碰撞检测
    level9CheckPlayerCollision(projectile) {
        try {
            if (!window.player || typeof window.player.takeDamage !== 'function') {
                return false;
            }
            
            if (typeof window.player.x !== 'number' || typeof window.player.y !== 'number') {
                return false;
            }
            
            const dx = projectile.x - window.player.x;
            const dy = projectile.y - window.player.y;
            
            if (isNaN(dx) || isNaN(dy) || !isFinite(dx) || !isFinite(dy)) {
                return false;
            }
            
            const distance = Math.sqrt(dx * dx + dy * dy);
            if (isNaN(distance) || !isFinite(distance)) {
                return false;
            }
            
            const collisionRadius = (projectile.radius || 5) + (window.player.radius || 15);
            
            if (distance < collisionRadius) {
                // 第9关的伤害处理更加小心
                try {
                    const damage = Math.max(1, Math.min(50, projectile.damage || 10)); // 限制伤害范围
                    window.player.takeDamage(damage);
                    
                    // 简化的伤害特效（第9关专用）
                    // this.level9CreateDamageEffect(window.player.x, window.player.y); // 禁用红色圆圈效果
                    
                    return true;
                } catch (damageError) {
                    console.warn('第9关伤害处理错误:', damageError);
                    return true; // 仍然移除投射物
                }
            }
            
            return false;
            
        } catch (collisionError) {
            console.warn('第9关碰撞检测错误:', collisionError);
            return false;
        }
    }
    
    // 第9关专用简化伤害特效 - 已禁用红色圆圈效果
    level9CreateDamageEffect(x, y) {
        // 禁用红色圆圈效果 - 此函数不再创建任何视觉效果
        return;
        /*
        try {
            // 只创建最简单的特效，避免复杂操作
            if (this.particles && Array.isArray(this.particles) && this.particles.length < 50) {
                this.particles.push({
                    x: x,
                    y: y,
                    vx: (Math.random() - 0.5) * 100,
                    vy: (Math.random() - 0.5) * 100,
                    life: 500,
                    maxLife: 500,
                    color: '#FF0000',
                    size: 3,
                    update: function(deltaTime) {
                        this.x += this.vx * deltaTime / 1000;
                        this.y += this.vy * deltaTime / 1000;
                        this.life -= deltaTime;
                        return this.life > 0;
                    },
                    render: function(ctx) {
                        try {
                            const alpha = this.life / this.maxLife;
                            ctx.fillStyle = `rgba(255, 0, 0, ${alpha})`;
                            ctx.fillRect(this.x - this.size/2, this.y - this.size/2, this.size, this.size);
                        } catch (renderError) {
                            // 渲染错误也不抛出异常
                        }
                    }
                });
            }
        } catch (effectError) {
            // 特效创建失败也不影响游戏
        }
        */
    }
    
    // 验证投射物数据完整性
    isValidProjectile(projectile) {
        return projectile && 
               typeof projectile.x === 'number' && 
               typeof projectile.y === 'number' && 
               typeof projectile.vx === 'number' && 
               typeof projectile.vy === 'number' &&
               !isNaN(projectile.x) && 
               !isNaN(projectile.y) &&
               !isNaN(projectile.vx) && 
               !isNaN(projectile.vy);
    }
    
    // 更新投射物位置
    updateProjectilePosition(projectile, deltaTime) {
        try {
            const timeStep = deltaTime / 1000;
            projectile.x += projectile.vx * timeStep;
            projectile.y += projectile.vy * timeStep;
            projectile.life -= deltaTime;
            return true;
        } catch (error) {
            console.warn('投射物位置更新失败:', error);
            return false;
        }
    }
    
    // 检查是否应该移除投射物
    shouldRemoveProjectile(projectile) {
        const margin = 100; // 边界缓冲区
        
        return projectile.life <= 0 || 
               projectile.x < -margin || 
               projectile.x > this.canvas.width + margin ||
               projectile.y < -margin || 
               projectile.y > this.canvas.height + margin;
    }
    
    // 检查投射物与玩家的碰撞
    checkProjectilePlayerCollision(projectile) {
        try {
            if (!window.player || typeof window.player.takeDamage !== 'function') {
                return false;
            }
            
            const dx = projectile.x - window.player.x;
            const dy = projectile.y - window.player.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            const collisionRadius = (projectile.radius || 5) + (window.player.radius || 15);
            
            if (distance < collisionRadius) {
                // 处理伤害
                window.player.takeDamage(projectile.damage || 10);
                
                // 创建简单的伤害特效
                this.createSimpleDamageEffect(window.player.x, window.player.y);
                
                // 根据投射物类型创建特效
                if (projectile.type === 'spit') {
                    this.createSimpleSpitEffect(projectile.x, projectile.y);
                }
                
                return true; // 发生碰撞
            }
            
            return false; // 没有碰撞
            
        } catch (collisionError) {
            console.warn('碰撞检测失败:', collisionError);
            return false;
        }
    }
    
    // 安全移除投射物
    removeProjectileAt(index, reason) {
        try {
            if (index >= 0 && index < this.zombieProjectiles.length) {
                this.zombieProjectiles.splice(index, 1);
                // console.log(`移除投射物: ${reason}`); // 减少日志输出
            }
        } catch (removeError) {
            console.warn('移除投射物失败:', removeError);
        }
    }
    
    // 创建简单伤害特效
    createSimpleDamageEffect(x, y) {
        try {
            this.ensureProjectileArrays();
            
            // 创建红色伤害粒子
            for (let i = 0; i < 3; i++) {
                this.particles.push({
                    x: x + (Math.random() - 0.5) * 20,
                    y: y + (Math.random() - 0.5) * 20,
                    vx: (Math.random() - 0.5) * 60,
                    vy: (Math.random() - 0.5) * 60 - 30,
                    life: 800,
                    maxLife: 800,
                    color: '#FF4444',
                    size: 2,
                    update: function(deltaTime) {
                        this.x += this.vx * deltaTime / 1000;
                        this.y += this.vy * deltaTime / 1000;
                        this.life -= deltaTime;
                        this.vy += 20 * deltaTime / 1000; // 重力
                        return this.life > 0;
                    },
                    render: function(ctx) {
                        const alpha = this.life / this.maxLife;
                        ctx.fillStyle = `rgba(255, 68, 68, ${alpha})`;
                        ctx.beginPath();
                        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                        ctx.fill();
                    }
                });
            }
        } catch (error) {
            console.warn('创建伤害特效失败:', error);
        }
    }
    
    // 创建简单吐液特效
    createSimpleSpitEffect(x, y) {
        try {
            this.ensureProjectileArrays();
            
            // 创建绿色腐蚀粒子
            for (let i = 0; i < 5; i++) {
                this.particles.push({
                    x: x,
                    y: y,
                    vx: (Math.random() - 0.5) * 80,
                    vy: (Math.random() - 0.5) * 80,
                    life: 1200,
                    maxLife: 1200,
                    color: '#90EE90',
                    size: 3,
                    update: function(deltaTime) {
                        this.x += this.vx * deltaTime / 1000;
                        this.y += this.vy * deltaTime / 1000;
                        this.life -= deltaTime;
                        this.vx *= 0.98; // 减速
                        this.vy *= 0.98;
                        return this.life > 0;
                    },
                    render: function(ctx) {
                        const alpha = this.life / this.maxLife;
                        ctx.fillStyle = `rgba(144, 238, 144, ${alpha})`;
                        ctx.beginPath();
                        ctx.arc(this.x, this.y, this.size * alpha, 0, Math.PI * 2);
                        ctx.fill();
                    }
                });
            }
        } catch (error) {
            console.warn('创建吐液特效失败:', error);
        }
    }
    
    // 定期维护和清理
    performMaintenance() {
        // 第9关每2秒维护一次，其他关卡每5秒
        const currentLevel = window.gameManager ? window.gameManager.levelManager.currentLevel : 1;
        const maintenanceInterval = currentLevel === 9 ? 2000 : 5000;
        
        if (!this.lastMaintenanceTime) {
            this.lastMaintenanceTime = Date.now();
            return;
        }
        
        if (Date.now() - this.lastMaintenanceTime < maintenanceInterval) {
            return;
        }
        
        this.lastMaintenanceTime = Date.now();
        
        try {
            // 确保数组完整性
            this.ensureProjectileArrays();
            
            // 第9关的特殊清理
            if (currentLevel === 9) {
                this.performLevel9Cleanup();
            }
            
            // 清理无效投射物
            let cleanedCount = 0;
            this.zombieProjectiles = this.zombieProjectiles.filter(projectile => {
                if (!this.isValidProjectile(projectile)) {
                    cleanedCount++;
                    return false;
                }
                return true;
            });
            
            if (cleanedCount > 0 && currentLevel === 9) {
                console.log(`第9关维护清理: 移除了 ${cleanedCount} 个无效投射物`);
            }
            
            // 清理过期粒子
            let particlesCleaned = 0;
            this.particles = this.particles.filter(particle => {
                if (!particle || particle.life <= 0) {
                    particlesCleaned++;
                    return false;
                }
                return true;
            });
            
            // 第9关性能监控
            if (currentLevel === 9) {
                this.monitorLevel9Performance();
            }
            
            // 只在必要时输出状态信息
            if (currentLevel === 9 || cleanedCount > 0 || particlesCleaned > 5) {
                console.log(`L${currentLevel} 状态 - 投射物: ${this.zombieProjectiles.length}, 粒子: ${this.particles.length}, 僵尸: ${this.zombies.length}`);
            }
            
        } catch (maintenanceError) {
            console.error('维护过程出错:', maintenanceError);
            // 紧急恢复
            this.emergencyCleanup();
        }
    }
    
    // 第9关特殊清理
    performLevel9Cleanup() {
        try {
            // 强制限制投射物数量
            if (this.zombieProjectiles.length > 10) {
                const excess = this.zombieProjectiles.length - 8;
                this.zombieProjectiles.splice(0, excess);
                console.log(`第9关强制清理: 移除了 ${excess} 个过量投射物`);
            }
            
            // 清理异常僵尸
            this.zombies = this.zombies.filter(zombie => {
                return zombie && 
                       typeof zombie.x === 'number' && 
                       typeof zombie.y === 'number' && 
                       !isNaN(zombie.x) && 
                       !isNaN(zombie.y) &&
                       zombie.health > 0;
            });
            
            // 强制垃圾回收建议（仅限现代浏览器）
            if (window.gc && typeof window.gc === 'function') {
                window.gc();
            }
            
        } catch (level9Error) {
            console.error('第9关清理失败:', level9Error);
        }
    }
    
    // 第9关性能监控
    monitorLevel9Performance() {
        const projectileCount = this.zombieProjectiles.length;
        const particleCount = this.particles.length;
        const zombieCount = this.zombies.length;
        
        // 性能警告阈值
        if (projectileCount > 8) {
            console.warn(`第9关投射物过多: ${projectileCount}, 强制清理`);
            this.zombieProjectiles.splice(0, projectileCount - 6);
        }
        
        if (particleCount > 50) {
            console.warn(`第9关粒子过多: ${particleCount}, 强制清理`);
            this.particles.splice(0, particleCount - 30);
        }
        
        if (zombieCount > 50) {
            console.warn(`第9关僵尸过多: ${zombieCount}, 可能有性能问题`);
        }
        
        // 内存使用情况检查
        if (performance && performance.memory) {
            const memUsed = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024);
            if (memUsed > 100) { // 超过100MB
                console.warn(`第9关内存使用较高: ${memUsed}MB`);
                this.emergencyCleanup();
            }
        }
    }
    
    // 紧急清理
    emergencyCleanup() {
        try {
            console.warn('执行紧急清理...');
            
            // 重置所有动态数组
            this.zombieProjectiles = [];
            this.particles = [];
            this.floatingTexts = [];
            this.bossProjectiles = [];
            
            // 清理无效僵尸
            this.zombies = this.zombies.filter(zombie => 
                zombie && zombie.health > 0 && 
                typeof zombie.x === 'number' && typeof zombie.y === 'number'
            );
            
            console.log('紧急清理完成');
            
        } catch (emergencyError) {
            console.error('紧急清理失败:', emergencyError);
        }
    }
    
    // 渲染僵尸投射物
    renderZombieProjectiles() {
        try {
            this.ensureProjectileArrays();
            
            if (!this.zombieProjectiles || this.zombieProjectiles.length === 0) {
                return;
            }
            
            this.zombieProjectiles.forEach(projectile => {
                try {
                    if (this.isValidProjectile(projectile)) {
                        this.renderSingleProjectile(projectile);
                    }
                } catch (renderError) {
                    console.warn('渲染单个投射物失败:', renderError);
                }
            });
            
        } catch (renderAllError) {
            console.warn('渲染僵尸投射物失败:', renderAllError);
        }
    }
    
    // 渲染单个投射物
    renderSingleProjectile(projectile) {
        try {
            const ctx = this.ctx;
            const alpha = Math.min(1, projectile.life / projectile.maxLife);
            
            ctx.save();
            
            // 根据投射物类型设置颜色
            let color = projectile.color || '#90EE90';
            if (projectile.type === 'spit') {
                color = '#90EE90'; // 绿色吐液
            }
            
            // 绘制投射物主体
            ctx.fillStyle = color;
            ctx.globalAlpha = alpha;
            ctx.beginPath();
            ctx.arc(projectile.x, projectile.y, projectile.radius || 5, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制光晕效果
            if (alpha > 0.5) {
                ctx.fillStyle = color;
                ctx.globalAlpha = (alpha - 0.5) * 0.3;
                ctx.beginPath();
                ctx.arc(projectile.x, projectile.y, (projectile.radius || 5) * 1.5, 0, Math.PI * 2);
                ctx.fill();
            }
            
            ctx.restore();
            
        } catch (renderError) {
            console.warn('渲染投射物失败:', renderError);
        }
    }
    
    isCollidingProjectile(projectile, target) {
        const dx = projectile.x - target.x;
        const dy = projectile.y - target.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        return distance < (projectile.radius + target.radius);
    }
    
    createCorrosionEffect(x, y) {
        // 创建腐蚀特效
        for (let i = 0; i < 8; i++) {
            this.particles.push({
                x: x,
                y: y,
                vx: (Math.random() - 0.5) * 100,
                vy: (Math.random() - 0.5) * 100,
                color: '#9ACD32',
                size: Math.random() * 4 + 2,
                life: 1000 + Math.random() * 1000,
                maxLife: 1000,
                alpha: 1
            });
        }
    }
    
    
    resetGame() {
        this.bullets = [];
        this.zombies = [];
        this.weapons = [];
        this.meleeWeapons = []; // 重置近战武器数组
        this.particles = [];
        this.powerUps = [];
        this.floatingTexts = [];
        this.bossProjectiles = [];
        this.zombieProjectiles = []; // 确保重置僵尸投射物数组
        this.boss = null;
        this.gameState = 'menu';
        
        // 重置视觉效果
        if (window.visualEffects) {
            window.visualEffects.reset();
        }
    }
}

// 粒子效果类
class Particle {
    constructor(x, y, vx, vy, color, lifeTime) {
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
        this.color = color;
        this.life = lifeTime;
        this.maxLife = lifeTime;
        this.size = Math.random() * 4 + 2;
    }
    
    update(deltaTime) {
        this.x += this.vx * deltaTime / 1000;
        this.y += this.vy * deltaTime / 1000;
        this.life -= deltaTime;
        this.vy += 100 * deltaTime / 1000; // 重力
    }
    
    render(ctx) {
        const alpha = this.life / this.maxLife;
        ctx.globalAlpha = alpha;
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x - this.size/2, this.y - this.size/2, this.size, this.size);
        ctx.globalAlpha = 1;
    }
}